package com.ruoyi.project.tool.swagger.UserController;

import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.WXPayUtil;
import com.ruoyi.common.utils.pay.AlipayConfig;
import com.ruoyi.framework.aspectj.lang.annotation.SignatureValidation;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysGoods;
import com.ruoyi.project.system.domain.SysGoodsFile;
import com.ruoyi.project.system.domain.SysGoodsOrder;
import com.ruoyi.project.system.service.ISysGoodsFileService;
import com.ruoyi.project.system.service.ISysGoodsOrderService;
import com.ruoyi.project.system.service.ISysGoodsService;
import com.ruoyi.project.system.service.ISysServiceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/mobileUser/goodsList/")
@RestController
public class UserGoodsListController extends BaseController {
    @Autowired
    private ISysGoodsService sysGoodsService;

    @Autowired
    private ISysGoodsOrderService sysGoodsOrderService;


    @Autowired
    private ISysServiceOrderService sysServiceOrderService;


    @Autowired
    private ISysGoodsFileService sysGoodsFileService;
    @GetMapping("/list")
    @SignatureValidation
    public TableDataInfo list(SysGoods sysGoods)
    {
        startPage();
        List<SysGoods> list = sysGoodsService.selectSysGoodsLists(sysGoods);
        if(!list.isEmpty()){
            for(SysGoods goods:list){
                SysGoodsFile sysGoodsFile=new SysGoodsFile();
                sysGoodsFile.setGoodsId(goods.getGoodsId());
                List<SysGoodsFile> files=sysGoodsFileService.selectSysGoodsFileList(sysGoodsFile);
                goods.setFiles(files);
            }
        }
        return getDataTable(list);
    }

    @RepeatSubmit
    @SignatureValidation
    @RequestMapping(value = "/createGoodsOrderService", method = RequestMethod.POST)
    public AjaxResult createGoodsOrderService(@RequestBody(required = false) SysGoodsOrder sysGoodsOrder){
        return sysGoodsOrderService.createGoodsOrderService(sysGoodsOrder);
    }

    @RequestMapping(value = "/payGoodsOrderService", method = RequestMethod.POST)
    @RepeatSubmit
    @SignatureValidation
    public AjaxResult payGoodsOrderService(@RequestBody SysGoodsOrder sysGoodsOrder){
        return sysGoodsOrderService.payGoodsOrderService(sysGoodsOrder);
    }

    @SignatureValidation
    @RequestMapping(value = "/getMyGoods", method = RequestMethod.POST)
    public TableDataInfo getMyGoods(SysGoodsOrder sysGoodsOrder){
        sysGoodsOrder.setMobileUserId(SecurityUtils.getLoginUser().getSysMobileUser().getMobileUserId());
        startPage();
        return getDataTable(sysGoodsOrderService.getMyGoods(sysGoodsOrder));
    }

    /**
     * 支付宝回调
     * @return
     */
    @RequestMapping(value = "/alipayBack", method = RequestMethod.POST)
    public void alipayBack(HttpServletRequest request, HttpServletResponse response){
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            // 支付金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            // 付款时间
            String gmt_create = new String(request.getParameter("gmt_create").getBytes("ISO-8859-1"), "UTF-8");
            // sellerId
            String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
            // appId
            String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
            // boolean AlipaySignature.rsaCheckV1(Map<String, String> params,
            // String publicKey, String charset, String sign_type)
            boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,
                    AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
            if (verify_result) {
                    if(out_trade_no.startsWith("G")&&out_trade_no.length()==14){
                        /**
                         * 二手物品订单表
                         */
                        if (sysGoodsOrderService.alipayBack(out_trade_no,"1",total_amount)) {
                            response.getWriter().println("success");
                            response.getWriter().close();
                        } else {
                            response.getWriter().println("failure");
                            response.getWriter().close();
                        }
                    }else if(out_trade_no.startsWith("S")&&out_trade_no.length()==14){
                        if (sysServiceOrderService.alipayBack(out_trade_no,"1",total_amount)) {
                            response.getWriter().println("success");
                            response.getWriter().close();
                        } else {
                            response.getWriter().println("failure");
                            response.getWriter().close();
                        }
                    }
            } else {// 验证失败
                response.getWriter().println("failure");
                response.getWriter().close();
            }
        } catch (Exception e) {
            try {
                response.getWriter().println("fail");
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                response.getWriter().close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }
    /**
     * 微信支付回调
     * @return
     */
    @RequestMapping(value = "/weiXinBack", method = RequestMethod.POST)
    public void weiXinBack(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> paramMap = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder stb = new StringBuilder();
            String line = null;
            while ((line = in.readLine()) != null) {
                stb.append(line);
            }
            in.close();
            paramMap = WXPayUtil.xmlToMap(stb.toString());
            String orderNo = paramMap.get("out_trade_no");
            String factPaySum = paramMap.get("total_fee");
            String tradeStatus = paramMap.get("result_code");
            if (tradeStatus.equals("SUCCESS")) {
                if(orderNo.startsWith("G")&&orderNo.length()==14){
                    /**
                     * 二手物品订单表
                     */
                    if (sysGoodsOrderService.alipayBack(orderNo,"2",ToolUtil.FenToyuan(factPaySum))) {
                        response.getWriter().println("success");
                        response.getWriter().close();
                    } else {
                        response.getWriter().println("failure");
                        response.getWriter().close();
                    }
                }else if(orderNo.startsWith("S")&&orderNo.length()==14){
                    if (sysServiceOrderService.alipayBack(orderNo,"2",ToolUtil.FenToyuan(factPaySum))) {
                        response.getWriter().println("success");
                        response.getWriter().close();
                    } else {
                        response.getWriter().println("failure");
                        response.getWriter().close();
                    }
                }
            }
            response.getWriter().print(WXPayUtil.setXml("fail", "未知错误"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RepeatSubmit
    @SignatureValidation
    @RequestMapping(value = "/sendGoods", method = RequestMethod.POST)
    public AjaxResult sendGoods(@RequestBody SysGoodsOrder sysGoodsOrder){
       return sysGoodsOrderService.sendGoods(sysGoodsOrder);
    }

    /**
     * 商家审核是否同意用户退货
     * @param sysGoodsOrder
     * @return
     */
    @RepeatSubmit
    @SignatureValidation
    @RequestMapping(value = "/auditGoods", method = RequestMethod.POST)
    public AjaxResult auditGoods(@RequestBody SysGoodsOrder sysGoodsOrder){
        return sysGoodsOrderService.auditGoods(sysGoodsOrder);
    }

}
